<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
$this->need('header.php'); // 包含头部文件

$db = Typecho_Db::get();
$options = Typecho_Widget::widget('Widget_Options');

// 查询所有内容
$query = $db->select()
    ->from('table.contents')
    ->where('type = ?', 'post') // 或其他类型，根据需要调整
    ->order('created', Typecho_Db::SORT_DESC);

try {
    $results = $db->fetchAll($query);
} catch (Typecho_Db_Exception $e) {
    echo 'Database Query Error: ' . $e->getMessage();
    return;
}

$images = [];
$imageReferences = [];
$patternLinks = '/\[(.*?)\]:\s*(https?:\/\/[^\s]+)/i'; // 提取链接标识符和 URL
$patternImages = '/!\[.*?\]\[(.*?)\]/i'; // 提取图像引用标识符

foreach ($results as $result) {
    $text = $result['text'];
    
    // 提取所有图像链接
    preg_match_all($patternLinks, $text, $matchesLinks, PREG_SET_ORDER);
    foreach ($matchesLinks as $match) {
        $imageReferences[$match[1]] = $match[2];
    }
    
    // 提取所有图像引用
    preg_match_all($patternImages, $text, $matchesImages, PREG_SET_ORDER);
    foreach ($matchesImages as $match) {
        if (isset($imageReferences[$match[1]])) {
            $imageUrl = $imageReferences[$match[1]];
            if (strpos($imageUrl, 'http') !== 0) {
                $imageUrl = $options->siteUrl . $imageUrl;
            }
            $images[] = [
                'url' => $imageUrl,
                'alt' => '' // 可以添加更多解析逻辑来提取 alt 文本
            ];
        }
    }
}
?>

<div class="archive-images">
    <?php foreach ($images as $image): ?>
        <div class="image-item">
            <a href="<?php echo htmlspecialchars($image['url']); ?>" target="_blank">
                <img src="<?php echo htmlspecialchars($image['url']); ?>" alt="<?php echo htmlspecialchars($image['alt']); ?>">
            </a>
        </div>
    <?php endforeach; ?>
</div>

<?php $this->need('footer.php'); // 包含底部文件 ?>
